package xxl.robotlegs.extensions.viewmanager 
{
	import flash.display.DisplayObjectContainer;
	import xxl.robotlegs.extensions.contextview.impl.ContextView;
	import xxl.robotlegs.extensions.viewmanager.api.IViewManager;
	import xxl.robotlegs.extensions.viewmanager.impl.ContainerBinding;
	import xxl.robotlegs.extensions.viewmanager.impl.ContainerRegistry;
	import xxl.robotlegs.extensions.viewmanager.impl.StageCrawler;
	import xxl.robotlegs.framework.api.IContext;
	import xxl.robotlegs.framework.api.IExtension;
	import xxl.robotlegs.framework.api.IInjector;
	import xxl.robotlegs.framework.api.ILogger;
	
	/**
	 * ...
	 * @author XXL
	 */
	public class StageCrawlerExtension implements IExtension 
	{
		private var _injector:IInjector;
		private var _logger:ILogger;
		private var _containerRegistry:ContainerRegistry;
		
		public function StageCrawlerExtension() 
		{
			
		}
		
		public function toString():String
		{
			return "StageCrawlerExtension（简介：对已经添加到场景上的所有容量，对其以及其容量自动执行handleView。必要依赖：ViewManagerExtension，ContextViewExtension）";
		}
		
		private function afterInitializing():void
		{
			_containerRegistry = _injector.getInstance(ContainerRegistry);
			_injector.hasDirectMapping(IViewManager)
				? scanViewManagedContainers()
				: scanContextView();
		}
		
		private function scanViewManagedContainers():void
		{
			_logger.debug("已经安装了ViewManager，检查其管理的所有容器。。。");
			const viewManager:IViewManager = _injector.getInstance(IViewManager);
			const containers:Vector.<DisplayObjectContainer> = viewManager.containers;
			const len:int = containers.length;
			for (var i:int = 0; i < len; i++) 
			{
				const container:DisplayObjectContainer = containers[i];
				container.stage && scanContainer(container);
			}
		}
		
		private function scanContainer(container:DisplayObjectContainer):void
		{
			const binding:ContainerBinding = _containerRegistry.getBinding(container);
			_logger.debug("StageCrawler正在扫描容器 {0} 。。。", [container]);
			new StageCrawler(binding).scan(container);
			_logger.debug("StageCrawler完成扫描 {0}", [container]);
		}
		
		private function scanContextView():void
		{
			_logger.debug("没有安装ViewManager，直接通过ContextView检查");
			const contextView:ContextView = _injector.getInstance(ContextView);
			contextView.view.stage && scanContainer(contextView.view);
		}
		
		/* INTERFACE xxl.robotlegs.framework.api.IExtension */
		
		public function extend(context:IContext):void 
		{
			_injector = context.injector;
			_logger = context.getLogger(this);
			context.afterInitializing(afterInitializing);
		}
		
	}

}